package com.tron.sync.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.tron.sync.entities.JZOrg;
import com.tron.sync.entities.JZUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 获取警宗平台用户，组织数据
 */

@Service
@Slf4j
public class JZServiceImpl {

    @Value("${jzUrl}")
    String url;
    @Value("${accessKey}")
    String accessKey;
    @Value("${secretKey}")
    String secretKey;
    @Value("${apiName1}")
    String apiName1;
    @Value("${apiName2}")
    String apiName2;
    @Value("${apiName3}")
    String apiName3;
    @Value("${version}")
    String version;

    @Autowired
    JZOrgService jzOrgService;

    String params = "{\"pageNum\":1,\"bzk_gxsj\":\"2019-10-12 14:42:49\",\"bzk_gxsj1\":\"2020-07-03 14:42:49\"}";
    RestTemplate restTemplate = new RestTemplate();

    /**
     * 辅警信息
     * csrq:"1971-11-07"    出生日期
     * systemid:""          标准库系统主键
     * jgmc:""              机构名称
     * hck_systemid:""      汇聚库系统主键
     * rksj:""              入库时间
     * bzk_scbz:""          标准库删库标识
     * jlbz_sfxxdm_ywxt:""   业务字典值
     * gmsfhm:""             公民身份号码
     * sjhm:""               手机号码
     * xbdm:""               性别代码
     * xbdm_ywxt:""          性别值
     * jlbz_sfxxdm_zw:""     字典中文值
     * bzk_rksj:""            标准入库时间
     * jlbz_sfxxdm:""        是否选项代码
     * xbdm_zw:""            任职单位字典中文值
     * pg_rksj:""            pg入库时间
     * xm:""                 姓名
     * gxsj:""               更新时间
     * pg_gxsj:""            pg更新时间
     * bzk_gxsj:""           标准库更新时间
     * ywk_ssxtmc:""         业务库系统名称
     * guid:""               全球统一标识符
     *
     *
     * 民警
     * zjmc:""         职级名称
     * ywk_ssxtmc:""
     * pg_gxsj:""
     * zw_mc:""        职务名称
     * xm:""           姓名
     * pg_rksj:""
     * sfky:""         是否可用
     * zw_bz:""        职务
     * rzztdm:""       任职状态代码
     * rzdw:""         任职单位
     * mjssjzdm:""     警种
     * csrq:""         出生日期
     * dwid:""         单位id
     * jgmc:""         机构名称
     * systemid:""
     * rzdw_ywxt:""             任职单位业务字典值
     * jlbz_sfxxdm_ywxt:""
     * gmsfhm:""                 身份证号码
     * xbdm:""                 性别代码
     * xbdm_ywxt:""            性别业务字典值
     * zwjb:""             职务级别
     * sfmr:""           是否默认
     * bzk_rksj:""
     * jcbh:""           警察编号
     * rzdm_zw:""         任职单位字典中文值
     * xzqhdm_ywxt:""
     * jlbz_sfxxdm:""
     * xzqhdm:""          行政区划代码
     * xbdm_zw:""         性别中文值
     * jzmc:""            警钟名称
     * xzqhdm_zw:""      行政区划代码中文字典值
     * bzk_gxsj:""
     * sjhm:""          手机号码
     * gw:""       岗位
     * gwmc:""     岗位名称
     *
     *
     *
     * 机构信息
     * systemid:""   系统id
     * jgmc:""       机构名称
     * dwjb:""        ----------
     * hck_systemid:""   系统主键
     * rksj:""           入库时间
     * bzk_scbz:""       标准库删库标识
     * jlbz_sfxxdm_ywxt:""
     * cjrq:""           创建日期
     * zzjg_ywxt:""       组织机构业务字典值
     * jlbz_sfxxdm_zw:""
     * bzk_rksj:""
     * jlbz_sfxxdm:""
     * pg_rksj:""
     * gxsj:""
     * pg_gxsj:""
     * jigdm_ywxt:""    机构代码业务字典值
     * ywk_ssxtmc:""
     * bzk_gxsj:""
     * pg_gxsj:""
     * zzjg:""      组织机构id
     * zzjg_zw:""   中文值
     *
     */


    /**
     * 获取辅警
     *
     * @param page
     * @return
     */
    public List<JZUser> getUsers01(Integer page) {
        restTemplate.setMessageConverters(Arrays.asList(new StringHttpMessageConverter(StandardCharsets.UTF_8)));
        String url = this.url + "?accessKey=" + accessKey + "&secretKey=" + secretKey + "&apiName=" + apiName1 + "&version=" + version + "&params={\"pageNum\":" + page + ",\"bzk_gxsj\":\"2019-10-12 14:42:49\",\"bzk_gxsj1\":\"2020-07-03 14:42:49\"}";
        URI uri = UriComponentsBuilder.fromUriString(url).build().encode(StandardCharsets.UTF_8).toUri();
        log.info("请求路径：" + uri);
        String forObject = restTemplate.getForObject(uri, String.class);
        JSONObject jsonObject = JSONObject.parseObject(forObject);
        JSONObject params = jsonObject.getJSONObject("params");
        JSONArray data = params.getJSONArray("data");

        ArrayList<JZUser> jzUsers = new ArrayList<>();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        data.forEach(d -> {
            JSONObject o = (JSONObject) d;
            JZUser jzUser = new JZUser();
            jzUser.setCardNo(o.getString("gmsfhm"));
            jzUser.setName(o.getString("xm"));
            try {
                jzUser.setGender(o.getString("xbmzwz").equals("男") ? "male" : "female");
            } catch (Exception e) {
                jzUser.setGender("");
            }
            jzUser.setPhoneNo(o.getString("sjhm"));
            jzUser.setPoliceCategory("T2");
            jzUser.setPoliceNo(o.getString("jcbh"));
            jzUser.setPoliceType(o.getString("jzmc"));
            jzUser.setOfficeId(o.getString("zw_bz"));
            jzUser.setOfficeName(o.getString("zw_mc"));
            jzUser.setOfficeRank(o.getString("zwjb"));
            jzUser.setOfficeStatus(o.getString("rzztdm"));
            jzUser.setPostId(o.getString("gw"));
            jzUser.setPostName(o.getString("gwmc"));
            jzUser.setRegionNo(o.getString("xzqhdm"));
            jzUser.setOrgId("ORG_ROOT");
            jzUser.setOrgName(o.getString("jgmc"));
            jzUser.setWpsSyncStatus(0);
            jzUser.setSyndaSyncStatus(0);
            try {
                jzUser.setBirthday(dateFormat.parse(o.getString("csrq")));
            } catch (Exception e) {
                log.info("处理出生日期错误：" + e.getMessage());
            }
            jzUsers.add(jzUser);
        });
        return jzUsers;
    }

    /**
     * 获取民警
     *
     * @param page
     * @return
     */
    public List<JZUser> getUsers02(Integer page) {
        restTemplate.setMessageConverters(Arrays.asList(new StringHttpMessageConverter(StandardCharsets.UTF_8)));
        String url = this.url + "?accessKey=" + accessKey + "&secretKey=" + secretKey + "&apiName=" + apiName2 + "&version=" + version + "&params={\"pageNum\":" + page + ",\"bzk_gxsj\":\"2019-10-12 14:42:49\",\"bzk_gxsj1\":\"2020-07-03 14:42:49\"}";
        URI uri = UriComponentsBuilder.fromUriString(url).build().encode(StandardCharsets.UTF_8).toUri();
        log.info("请求路径：" + uri);
        String forObject = restTemplate.getForObject(uri, String.class);
        JSONObject jsonObject = JSONObject.parseObject(forObject);
        JSONObject params = jsonObject.getJSONObject("params");
        JSONArray data = params.getJSONArray("data");
        ArrayList<JZUser> jzUsers = new ArrayList<>();
        data.forEach(d -> {
            JSONObject o = (JSONObject) d;
            JZUser jzUser = new JZUser();
            jzUser.setCardNo(o.getString("gmsfhm"));
            jzUser.setName(o.getString("xm"));
            try {
                jzUser.setGender(o.getString("xbmzwz").equals("男") ? "male" : "female");
            } catch (Exception e) {
                jzUser.setGender("");
            }
            jzUser.setPhoneNo(o.getString("sjhm"));
            jzUser.setPoliceCategory("T1");
            jzUser.setPoliceNo(o.getString("jcbh"));
            jzUser.setPoliceType(o.getString("jzmc"));
            jzUser.setOfficeId(o.getString("zw_bz"));
            jzUser.setOfficeName(o.getString("zw_mc"));
            jzUser.setOfficeRank(o.getString("zwjb"));
            jzUser.setOfficeStatus(o.getString("rzztdm"));
            jzUser.setPostId(o.getString("gw"));
            jzUser.setPostName(o.getString("gwmc"));
            jzUser.setRegionNo(o.getString("xzqhdm"));
            jzUser.setOrgId("ORG_ROOT");
            jzUser.setOrgName(o.getString("jgmc"));
            jzUser.setWpsSyncStatus(0);
            jzUser.setSyndaSyncStatus(0);
            try {
                jzUser.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(o.getString("csrq")));
            } catch (Exception e) {
                log.info("处理出生日期错误：" + e.getMessage());
            }
            jzUsers.add(jzUser);
        });
        return jzUsers;
    }

    /**
     * 获取机构
     *
     * @param page
     * @return
     */
    public List<JZOrg> getOrg(Integer page) {
        restTemplate.setMessageConverters(Arrays.asList(new StringHttpMessageConverter(StandardCharsets.UTF_8)));
        String url = this.url + "?accessKey=" + accessKey + "&secretKey=" + secretKey + "&apiName=" + apiName3 + "&version=" + version + "&params={\"pageNum\":" + page + ",\"bzk_gxsj\":\"2019-10-12 14:42:49\",\"bzk_gxsj1\":\"2020-07-03 14:42:49\"}";
        URI uri = UriComponentsBuilder.fromUriString(url).build().encode(StandardCharsets.UTF_8).toUri();
        log.info("请求路径：" + uri);
        String forObject = restTemplate.getForObject(uri, String.class);
        JSONObject jsonObject = JSONObject.parseObject(forObject);
        JSONObject params = jsonObject.getJSONObject("params");
        JSONArray data = params.getJSONArray("data");
        ArrayList<JZOrg> jzOrgs = new ArrayList<>();
        data.forEach(d -> {
            JSONObject o = (JSONObject) d;
            JZOrg jzOrg = new JZOrg();
            jzOrg.setId(o.getString("hck_systemid"));
            jzOrg.setName(o.getString("jgmc"));
            jzOrg.setOrgParentId(o.getString("ORG_ROOT"));
            jzOrg.setOrgParentName("云南省公安厅");
            jzOrg.setWpsSyncStatus(0);
            jzOrg.setSyndaSyncStatus(0);
            //TODO 胡祖有
            jzOrg.setZzjg(StringUtils.isEmpty(o.getString("zzjg"))?"未获取到数据":o.getString("zzjg"));
            jzOrg.setZzjgYwxt(StringUtils.isEmpty(o.getString("zzjg_ywxt"))?"未获取到数据":o.getString("zzjg_ywxt"));
            jzOrg.setZzjgZw(StringUtils.isEmpty(o.getString("zzjg_zw"))?"未获取到数据":o.getString("zzjg_zw"));
            jzOrg.setJigdm(StringUtils.isEmpty(o.getString("jigdm"))?"未获取到数据":o.getString("jigdm"));
            jzOrg.setJigdmYwxt(StringUtils.isEmpty(o.getString("jigdm_ywxt"))?"未获取到数据":o.getString("jigdm_ywxt"));
            jzOrg.setJigdmZw(StringUtils.isEmpty(o.getString("jigdm_zw"))?"未获取到数据":o.getString("jigdm_zw"));

            jzOrgs.add(jzOrg);
        });
        return jzOrgs;
    }

}
